// pages/payInfo/payInfo.js
var util = require('../../utils/util.js')
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: 30*60,
    formatTime: '',
    orderId: '',
    totalAmount: 0,
    payAmount: 0,
    msg: '',
    showToast: true, // 防止支付弹框延时弹出，再下一个页面弹出显示
    productGroupId: 2,
    code: '',
    payxcs: null,
    shareCode: '' //红包码
  },
  getFormatedTime (time) {
    time = new Date(time*1000)
    let sec = time.getSeconds()
    let min = time.getMinutes()
    return [min, sec].map(util.formatNumber).join(':')
  },
  countDown () {
    // 订单倒计时
    let _self = this
    if (this.data.time < 0) {
      return false
    } else {
      this.data.time--
      this.setData({
        time: this.data.time,
        formatTime: _self.getFormatedTime(this.data.time)
      })
      setTimeout(this.countDown, 1000) 
    }
  },
  getOrderInfo () {
    let _self = this
    this.loading()
    wx.login({
      success: function(res) {
        wx.request({
          url: app.globalData.baseUrl + '/pay/getPayInfo',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          data: { code: res.code, payOrderId: _self.data.orderId },
          method: 'POST',
          success: res => {
            res = res.data
            if (res.code === 0) {
              let diffTime = res.data.expireTime - Date.parse(new Date()) / 1000
              console.log(diffTime)
              _self.setData({
                totalAmount: res.data.totalAmount,
                payAmount: res.data.payAmount,
                time: diffTime,
                productGroupId: res.data.productGroupId
              })
              _self.countDown()
              let result = _self.wxlogin()
              result.then(success => {
                _self.wxpay(success)
              }, error => {

              }).catch(res => {

              })
            }
          },
          error: res => {
          }
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  loading () {
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  continueLogin () {
    this.loading()
    if (this.data.time > 0) {
      this.wxpay(this.data.payxcs)
    } else {
      wx.showModal({
        title: '警告',
        content: '订单支付已超时，请重新下单！',
        showCancel: false,
        confirmText: '确定',
        success: function(res) {
        },
        fail: function(res) {
        },
        complete: function(res) {},
      })
    }
  },
  wxlogin () {
    let _self = this
    return new Promise((resolve, reject) => {
      wx.login({
        success: function (res) {
          wx.request({
            url: app.globalData.baseUrl + '/wxpay/payXcx',
            data: { code: res.code, payOrderId: _self.data.orderId },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST',
            success: res => {
              console.log(res.data)
              _self.setData({
                payxcs: res.data
              })
              resolve(res.data)
            },
            error: res => {
              reject(res)
            }
          })
        },
        fail: function (res) { reject(res)}
      })
    })
  },
  gotoSuccess(flag, topicId) {
    let _self = this
    // 获取用户订单红包
    wx.login({
      success: (res) => wx.request({
        url: app.globalData.baseUrl + '/boon/createOrderBoon',
        data: { code: res.code, payOrderId: _self.data.orderId },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        method: 'POST',
        success: res => {
          res = res.data
          console.log(res)
          if (res.code === 0) {
            this.setData({
              shareCode: res.data.shareCode
            })
          }
          wx.redirectTo({
            url: '/pages/paySuccess/paySuccess?payResult=' + flag + '&productGroupId=' + _self.data.productGroupId + '&payOrderId=' + _self.data.orderId + '&topicId=' + topicId + '&shareCode=' + encodeURIComponent(_self.data.shareCode)
          })
        },
        error: res => {

        }
      })
    })
  },
  wxpay (res) {
    let _self = this
    console.log('---------------', res, this.data.showToast)
    if (res.code === 0 && this.data.showToast) {
      let data = res.data.payJsParam
      let storagetopicId = res.data.topicId
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType || 'MD5',
        paySign: data.paySign,
        success: function (res) {
          wx.hideLoading()
          // 付款成功
          _self.gotoSuccess(2, storagetopicId)
        },
        fail: function (res) {
          wx.hideLoading()
          if (res.errMsg != 'requestPayment:fail cancel') {
            // 不是用户取消付款情况下的付款失败
            _self.gotoSuccess(1, storagetopicId)
          }
        },
        complete: function (res) {
          _self.setData({
            showToast: true
          })
        },
      })
    } else if (res.code === -1){
      wx.hideLoading()
      _self.setData({
        msg: res.msg
      })
    } else {
      wx.hideLoading()
    }
  },
  naviBack () {
    this.setData({
      showToast: false
    })
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.payOrderId) {
      this.setData({
        orderId: options.payOrderId,
        showToast: true
      })
      this.getOrderInfo()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showToast: false
    })
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})